package com.hnepri.fang.ftx2.fetch.index;

import com.hnepri.fang.ftx2.fetch.APageBridge;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;

public class ResidentialIndexPageBridgeConcrete extends APageBridge {
    public String getHtml(String url) throws IOException {
        URL _url = new URL(url);

        HttpURLConnection urlConnection = (HttpURLConnection)_url.openConnection();
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setConnectTimeout(5000);//5秒连接时间
        urlConnection.setReadTimeout(5000);//5秒读取时间

        urlConnection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
        urlConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");
        urlConnection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
        urlConnection.setRequestProperty("Cache-Control", "no-cache");
        urlConnection.setRequestProperty("Connection", "keep-alive");
        urlConnection.setRequestProperty("Host", "zz.esf.fang.com");
        urlConnection.setRequestProperty("Pragma", "no-cache");
        urlConnection.setRequestProperty("Upgrade-Insecure-Requests", "1");
        urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");


        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        InputStream is = urlConnection.getInputStream();
        //BufferedReader br = new BufferedReader(new InputStreamReader(new DeflaterInputStream(is)));
        BufferedReader br = new BufferedReader(new InputStreamReader(new GZIPInputStream(is), "GB2312"));
        StringBuilder sb = new StringBuilder();
        String msg = null;

        while((msg = br.readLine()) != null) {
            sb.append(msg);
        }
        urlConnection.disconnect();
        return sb.toString();
    }
    @Override
    public String getPageInfo(String url) throws IOException {
        String html = this.getHtml(url);
        return this.page.parse(html);
    }
}
